#include "ItemNumberDialog.h"

ItemNumberDialog::ItemNumberDialog( DBMS *dbms, QWidget *parent ) : QDialog(parent)
{
    setWindowTitle( tr("Number of item") );

    this->dbms = dbms;
    DB = dbms->GetDatabase( "Materials" );

    SearchDialog = 0;

    ItemLabel = new QLabel(tr("Item:"));
    ItemEdit = new QLineEdit();
    ItemEdit->setEnabled( false );
    ChooseButton = new QPushButton(tr("Choose"));

    ItemLayout = new QHBoxLayout();
    ItemLayout->addWidget( ItemLabel );
    ItemLayout->addWidget( ItemEdit );
    ItemLayout->addWidget( ChooseButton );


    NumberLabel = new QLabel(tr("Number"));
    NumberEdit = new QLineEdit();

    NumberLayout = new QHBoxLayout();
    NumberLayout->addWidget( NumberLabel );
    NumberLayout->addWidget( NumberEdit );


    OkButton = new QPushButton(tr("Ok"));
    OkButton->setDefault( true );
    CancelButton = new QPushButton(tr("Cancel"));

    ControlLayout = new QHBoxLayout();
    ControlLayout->addWidget( OkButton );
    ControlLayout->addWidget( CancelButton );


    MainLayout = new QVBoxLayout();
    MainLayout->addLayout( ItemLayout );
    MainLayout->addLayout( NumberLayout );
    MainLayout->addLayout( ControlLayout );

    this->setLayout( MainLayout );


    //Signals and Slots
    connect( CancelButton, SIGNAL(clicked()), this, SLOT(close()) );
    connect( OkButton, SIGNAL(clicked()), this, SLOT(OkPressed()) );
    connect( ChooseButton, SIGNAL(clicked()), this, SLOT(ChoosePressed()) );
}

ItemNumberDialog::~ItemNumberDialog()
{
    delete MainLayout;
    //delete ControlLayout;
    //delete NumberLayout;
    //delete ItemLayout;

    delete OkButton;
    delete CancelButton;
    delete ChooseButton;

    delete ItemLabel;
    delete NumberLabel;

    delete ItemEdit;
    delete NumberEdit;

    if (SearchDialog != 0) delete SearchDialog;
}

void ItemNumberDialog::ChoosePressed()
{
    //Output( message, "ChoosePressed slot is executed");
    if (SearchDialog == 0) {
        SearchDialog = new DatabaseSearchDialog( DB , DB->GetKeyField(), this);
        connect( SearchDialog, SIGNAL(Item(const ItemType&)), this, SLOT(Item(const ItemType&)) );
    }

    SearchDialog->show();
}

void ItemNumberDialog::OkPressed()
{
    bool ok = false;
    number = NumberEdit->text().toInt( &ok, 10);

    if ( !ItemChoosen ) {
        Output( warning, tr("No item is choosen") );
        return;
    }

    if ( !ok ) {
        Output( warning, tr("Number is invalid") );
        return;
    }

    emit Item( item, number );
    emit this->close();
}

void ItemNumberDialog::Item( const ItemType& item )
{
    ItemChoosen = true;
    this->item = item;

    ItemEdit->setText( item.Get( DB->GetKeyField() ) );

    NumberEdit->setFocus();
}

void ItemNumberDialog::closeEvent ( QCloseEvent * event )
{
    Clear();
}

void ItemNumberDialog::Clear()
{
    ItemEdit->clear();
    NumberEdit->clear();
}
